﻿using Ding.Dependency;
using Ding.Files;
using Ding.Schedulers.Quartz;
using GitDC.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Quartz;
using System;
using System.IO;
using System.Threading.Tasks;

namespace GitDC.Jobs
{
    /// <summary>
    /// 数据库备份
    /// </summary>
    public class BackupDataBaseJob : JobBase
    {

        /// <summary>
        /// 获取重复执行间隔时间，单位：小时
        /// </summary>
        public override int? GetIntervalInHours()
        {
            return 1;
        }

        /// <summary>
        /// 执行
        /// </summary>
        /// <remarks>请使用 scope 参数创建实例，不要使用 Ioc.Create 方法，可能导致生命周期错误</remarks>
        protected override async Task Execute(IJobExecutionContext context, IScope scope)
        {
            var env = scope.Create<IWebHostEnvironment>();
            if (!env.IsDevelopment())
            {
                var FilePath = FileHelpers.WebMapPath("/db_back/") + DateTime.Now.ToString("yyyyMMddHHmmss");

                var path = FilePath + ".sql";
                DbBackup.BackupDb(path);

                var destFile = FilePath + ".zip";
                path.AsFile().Compress(destFile);  //压缩文件

                FileHelpers.DeleteFiles(path, false);
            }

            await Task.FromResult(0);
        }
    }
}
